'use strict'
const logger = require('../utils/logger')
const { uuid } = require('../utils/index')



module.exports =  (options) => {
    const IGNORE = options.ignore;
    return async (ctx, next) => {
        if (IGNORE.test(ctx.url)) {
            return await next();
        }
        const start = new Date().getTime();
        ctx.query.traceId = uuid();
        ctx.query._t = start;
        await next();
        let duration = new Date().getTime() - start;
        ctx.set('X-Response-Time', `${duration}ms`);
        logger.info([
            `traceId: ${ctx.query.traceId}`,
            `time: ${ctx.query._t}`,
            `url: ${ctx.originalUrl}`,
            `method: ${ctx.method}`,
            `params: ${JSON.stringify(ctx.query || ctx.request.fields)}`,
            `duration: ${duration}`
        ].join(' | '));
    }
}
